﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using CodingDay.Rx.Adaptors;
using CodingDay.Rx.Shared;
using CodingDay.Rx.Shared.Domain;
using CodingDay.Rx.Shared.Events;
using CodingDay.Rx.Shared.Interfaces;
using Holsee.Lib;

namespace CodingDay.Rx.ReactiveControllers
{
    public class ReactiveFeedController : IReactiveFeedController
    {
        public ReactiveFeedController()
        {
            Feeds = new List<IInputAdaptor>();
        }

        #region IReactiveFeedController Members

        public IObservable<IEvent<DTOReceivedArgs>> DTOEventStream { get; set; }

        #endregion

        #region Implementation of IReactiveFeedController

        private readonly List<Task> _feedTasks = new List<Task>();
        public IList<IInputAdaptor> Feeds { get; private set; }

        public void Initialize()
        {
            Feeds.Add(new ServerFeedAdaptor());

            DTOEventStream = Observable.FromEvent<DTOReceivedArgs>(Feeds[0], "OnDataReceived");

            StartAllFeeds();
        }

        public void Stop()
        {
            Feeds.ForEach(feed => feed.Stop());
        }

        private void StartAllFeeds()
        {
            _feedTasks.Clear();

            Feeds.ForEach(feed => _feedTasks.Add(new Task(feed.Start)));

            _feedTasks.ForEach(task => task.Start());
        }

        #endregion
    }
}